<template>
  <div class="page">
    <BackPage title="修改资料" show-back @back="onPageBack" />
    <div class="user1-add-box f-g">
      <el-form ref="formRef" :model="ruleForm" :rules="rules" label-position="top" class="user-add-form">
        <el-form-item label="头像" prop="headPortrait">
          <DragUpload :url="ruleForm.headPortrait" @on-success="url => ruleForm.headPortrait = url" />
        </el-form-item>
        <el-form-item label="姓名" prop="realname">
          <el-input clearable v-model="ruleForm.realname" style="width: 658px;" />
        </el-form-item>
        <el-form-item label="手机号" prop="mobile">
          <el-input clearable v-model="ruleForm.mobile" type="number" style="width: 658px;" />
        </el-form-item>
        <el-form-item label="旧密码" prop="oldPassword">
          <el-input clearable v-model="ruleForm.oldPassword" type="password" style="width: 658px;" />
        </el-form-item>
        <el-form-item label="新密码" prop="newPassword">
          <el-input clearable v-model="ruleForm.newPassword" type="password" style="width: 658px;" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="onSave">保存</el-button>
          <el-button @click="onPageBack">取消</el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script>

import { checkPhone } from '@/utils/validate'
import { mapGetters } from 'vuex'
import { updateUserInfo } from '@/api/user'

export default {
  name: 'UserInfo',
  computed: {
    ...mapGetters(['userInfo'])
  },
  data() {
    return {
      ruleForm: {
        id: undefined,
        realname: '',
        mobile: '',
        oldPassword: '',
        newPassword: '',
        headPortrait: '',
      },
      rules: {
        username: [{ required: true, message: '不能为空' }],
        realname: [{ required: true, message: '不能为空' }],
        mobile: [{ required: true, validator: checkPhone }],
        oldPassword: [{ required: true, message: '不能为空' }],
        newPassword: [{ required: true, message: '不能为空' }],
      }
    }
  },
  created() {
    this.ruleForm.realname = this.userInfo.realname
    this.ruleForm.mobile = this.userInfo.mobile
    this.ruleForm.headPortrait = this.userInfo.headPortrait
  },
  methods: {
    onPageBack() {
      this.$router.back()
    },
    onSave() {
      this.$refs.formRef.validate(valid => {
        if (valid) {
          updateUserInfo({
            ...this.ruleForm
          }).then(res => {
            this.$message.success(res.msg)
            this.$store.dispatch('user/logout')
          })
        }
      })
    }
  }
}
</script>

<style scoped lang="scss">
.user1-add-box {
  width: 100%;
  background: #FFFFFF;
  border: 1px solid rgba(185, 185, 185, .3);
  border-radius: 16px;
  padding: 60px;
}
</style>
